package com.example.travelexpensemanager;

import java.math.BigInteger;
import java.util.ArrayList;

public class MoneyDistribution {

	/*
	 * Here the reference to the toGet and toGive columns have been sent so the
	 * object is actually in ResultScreen. We are only receiving the reference
	 * on that object
	 */
	/*
	 * Algorithm to apply first fit algorithm to satisfy money to give and to
	 * get requests
	 */
	public static ArrayList<String> FirstFitAlgorithm(
			ArrayList<String> memberList, ArrayList<String> toGet,
			ArrayList<String> toGive, int turn) {
		ArrayList<String> messages = new ArrayList<String>();
		BigInteger get = new BigInteger("0"), give = new BigInteger("0");
		/* A loop in the to give column */
		for (int i = 0; i < toGive.size(); i++) {
			give =  new BigInteger(toGive.get(i));
			if (give.intValue() != 0) {
				/* A loop in the to get column */
				for (int j = 0; j < toGet.size(); j++) {
					get = new BigInteger(toGet.get(j));
					if (get.intValue() >= give.intValue()) {
						/*
						 * Means since he will be getting money so we need to
						 * subtract
						 */
						toGet.set(j, String.valueOf(get.intValue() - give.intValue()));
						/*
						 * After satisfying the request the person who gave
						 * everything should obviously give everything and have
						 * 0 to give
						 */
						toGive.set(i, String.valueOf(0));
						if (turn == 0)
							messages.add(memberList.get(i) + " pays "
									+ give + " to " + memberList.get(j));
						else if (turn == 1)
							messages.add(memberList.get(j) + " pays "
									+ give + " to " + memberList.get(i));
						break;
					}
				}
			}
		}

		return messages;
	}

	/*Function to check if again the first fit algorithm has to be run or not*/
	public static boolean checkIfAnyPersonStillHasToGiveMoney(
			ArrayList<String> toGet, ArrayList<String> toGive) {

		/*Checking if there is any non zero value in the toGive list i.e if any one has yet money to give*/
		for (String str : toGive)
			if ((new BigInteger(str)).intValue() != 0)
				return true;

		/*Return false if all are zeroes*/
		return false;
	}
}
